//
//  MJRegisterViewController.m
//  MJ
//
//  Created by qiaoBu on 2017/12/11.
//  Copyright © 2017年 lina. All rights reserved.
//

#import "MJRegisterViewController.h"
#import "MJRegisterView.h"
#import "MJLoginViewController.h"
#import "MJLoginViewModel.h"
#import "MJRegisterViewModel.h"
#import "MJChooseImageView.h"
//相册
#import <AssetsLibrary/AssetsLibrary.h>
//相机
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "MJMyInfoViewModel.h"
#import "MJChangeHeaderImageTool.h"
#import "MJRuleViewController.h"

@interface MJRegisterViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) MJRegisterView *registerView;
@property (nonatomic, strong) MJChooseImageView *chooseImageView;
@property (nonatomic, copy) NSString *spic;

@end

@implementation MJRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navgationBar.titleLabel.text = @"注册";
    self.view.backgroundColor = RGBColor(242,242,242);
    [self commonInit];
}

- (void)commonInit{
    
    _registerView = [[MJRegisterView alloc] initWithFrame:CGRectMake(0, self.navgationBar.height+15, kScreenWidth, kScreenHeight-15-64)];
    [self.view addSubview:_registerView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        MJRuleViewController *ruleVc = [[MJRuleViewController alloc] init];
        [self.navigationController pushViewController:ruleVc animated:YES];
    }];
    [_registerView.ruleButton addGestureRecognizer:tap];
    
    if ([self.sexString isEqualToString:@"1"])
    {
         _registerView.headerImageView.image = [UIImage imageNamed:@"boy"];
    }
    else
    {
         _registerView.headerImageView.image = [UIImage imageNamed:@"girl"];
    }
    [self initChooseImage];
    
    @weakify(self)
    [_registerView setRequestVerificationCodeBlcok:^(NSString *telePhone) {
        
        @strongify(self)
       if (self.registerView.telephoneField.text.length)
       {
           [self requestTelephoneCodeWithTelePhone:telePhone];
       }
       else
       {
           [TJMBProgressView showTingJianText:@"请输入手机号"];
       }
    }];
    
    [_registerView setLoginBlock:^{
       
     @strongify(self)
        
      MJLoginViewController *loginController = (MJLoginViewController *) [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] -3)];

      [self.navigationController popToViewController:loginController animated:YES];
        
    }];
    
    [_registerView setRegisterBlock:^(NSString *telePhone, NSString *verificationCode, NSString *name) {
        @strongify(self)

        [self registerWithTelePhone:telePhone verificationCode:verificationCode nickName:name];
    }];
    
    [_registerView setChangeHeaderImageBlock:^{
       
        @strongify(self)
        self.chooseImageView.hidden = NO;
    }];
    
  
}
- (void)initChooseImage{
    
    [[UIApplication sharedApplication].keyWindow addSubview:self.chooseImageView];
    self.chooseImageView.hidden = YES;
    
    @weakify(self)
    [self.chooseImageView setChooseImageBlock:^(NSInteger buttonTag) {
        @strongify(self)
        
        ALAuthorizationStatus  author = [ALAssetsLibrary authorizationStatus];
        if(author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied)
        {
            UIAlertView *authorAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要访问你的相册，请在设置-->隐私-->相册，中开启本应用的相册访问权限！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [authorAlertView show];
        }
        else
        {
            
            if (buttonTag == 10)
            {
                if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
                {
                    //相机
                    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                    imagePickerController.delegate = self;
                    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [self presentViewController:imagePickerController animated:YES completion:0];
                }
            }
            else
            {
                if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])
                {
                    //相册集
                    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                    imagePickerController.delegate = self;
                    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    [self presentViewController:imagePickerController animated:YES completion:0];
                }
            }
        }
        
    }];
}
#pragma mark - imagePicker代理
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [self dismissViewControllerAnimated:YES completion:0];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (image)
    {
        //刷新数据
        self.registerView.headerImageView.image = image;
        [self submitImageToServiceWithImage:image];
    }
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

- (void)submitImageToServiceWithImage:(UIImage *)image{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置时间格式
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
    
    NSMutableDictionary *picDict = [NSMutableDictionary dictionary];
    [picDict setObject:@"1" forKey:@"type"];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
    
    NSString *totalPath = [MJChangeHeaderImageTool saveImageData:imageData toDocumentsWithFileName:fileName];
    NSLog(@"totalPath ---------- %@",totalPath);
     [TJMBProgressView showTingJianTextNeverDismiss:@"上传中" Frame:self.view.bounds toView:self.view];
    [MJMyInfoViewModel requestUploadHeadImageWithImagePath:totalPath andNSMutableDictionary:picDict Success:^(NSString *stateCode, NSString *imageUrl, NSString *messageState) {
        
        [TJMBProgressView hideHUDForView:self.view];
        if ([stateCode isEqualToString:@"001"])
        {
            self.spic = [NSString stringWithFormat:@"%@",imageUrl];
        }
        else
        {
          [TJMBProgressView showTingJianText:messageState];
        }
        [MJChangeHeaderImageTool deleteImageResourceWithPath:totalPath];
    } failure:^(NSError *error) {
        
        [TJMBProgressView hideHUDForView:self.view];
        [TJMBProgressView showTingJianText:networkError];
        
    } netWorkState:^(BOOL netWorkState) {
        
    }];
}
#pragma mark -获取验证码
- (void)requestTelephoneCodeWithTelePhone:(NSString *)telePhone{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:telePhone forKey:@"mobile"];
    [MJLoginViewModel requestCodeWithDict:parameters success:^(NSString *state, NSString *message) {
        
        NSLog(@"%@---%@",state,message);
        if ([state isEqualToString:@"001"])
        {
            [self verificationCodeButtonCountDown];
        }
        else
        {
            [TJMBProgressView showTingJianText:message];
        }
        
    } failure:^(NSError *error) {
        
        NSLog(@"%@",error);
        [TJMBProgressView showTingJianText:networkError];
    } netWorkState:^(BOOL netWorkState) {
        
    }];
}
#pragma mark - 注册
- (void)registerWithTelePhone:(NSString *)telePhone verificationCode:(NSString *)verificationCode nickName:(NSString *)nickName{

    if (self.registerView.nameField.text.length &&self.registerView.verifyCodeField.text.length && self.registerView.nameField.text.length)
    {
        [TJMBProgressView showTingJianTextNeverDismiss:@"上传中" Frame:self.view.bounds toView:self.view];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:telePhone forKey:@"mobile"];
        [parameters setObject:verificationCode forKey:@"code"];
        [parameters setObject:self.sexString forKey:@"sex"];
        if (self.spic) {
            [parameters setObject:self.spic forKey:@"spic"];
        }else{
            
            [parameters setObject:@"0" forKey:@"spic"];
        }
        [parameters setObject:nickName forKey:@"alias"];
        
        [MJRegisterViewModel requestRegisterWithDict:parameters Success:^(NSString *state, NSString *message) {
            
            [TJMBProgressView hideHUDForView:self.view];
            if ([state isEqualToString:@"001"])
            {
                MJBaseViewController *controller = (MJBaseViewController *) [self.navigationController.viewControllers objectAtIndex: ([self.navigationController.viewControllers count] -4)];
                
                [self.navigationController popToViewController:controller animated:YES];
            }
            else
            {
                [TJMBProgressView showTingJianText:message];
            }
            
        } failure:^(NSError *error) {
            
            [TJMBProgressView hideHUDForView:self.view];
            [TJMBProgressView showTingJianText:networkError];
        } netWorkState:^(BOOL netWorkState) {
            
        }];
    }
    else
    {
         [TJMBProgressView showTingJianText:@"请先完善信息"];
    }
}
- (void)verificationCodeButtonCountDown{
    
    __block int time = 60;
    __block UIButton *verifybutton = _registerView.verifyCodeBtn;
    verifybutton.userInteractionEnabled = NO;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time<=0)
        {
            //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [verifybutton setTitle:@"重新获取验证码" forState:UIControlStateNormal];
                verifybutton.userInteractionEnabled = YES;
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSString *strTime = [NSString stringWithFormat:@"获取验证码(%d)",time];
                [verifybutton setTitle:strTime forState:UIControlStateNormal];
//                verifybutton.width += 20;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_registerView.nameField resignFirstResponder];
    [_registerView.telephoneField resignFirstResponder];
    [_registerView.verifyCodeField resignFirstResponder];
}
- (MJChooseImageView *)chooseImageView{
    
    if (!_chooseImageView)
    {
        _chooseImageView = [[MJChooseImageView alloc] initWithFrame:self.view.bounds];
    }
    return _chooseImageView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
